﻿using Network.UpdateData;
using SFJDManagement.SocketHandle;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace SFJDManagement
{
    public static class CSendMsg
    {
        /// <summary>
        /// 需要与服务器交换的数据：聊天消息，划号信息，委托人信息
        /// 1001  聊天消息
        /// 2001  客户端划号信息
        /// 2101  服务器返回划号号码
        /// 2102  服务器返回有重复的编码
        /// 3001  客户端添加的委托人信息
        /// </summary>
        private const int msgInPort = PacketHandle.msgInPort;
        private const int socketLenght = Packet.BytesCount;
        private static byte[] msgOut = new byte[socketLenght];
        
        public static void SendMsgWait(byte[] bytes)
        {
            //sSocket.Send(Encoding.UTF8.GetBytes("2030a8c780ef-f56f-4798-bdad-08f619394280♠省份♠城市♠地区♠名称♠全名♠ASDFSS♠地址♠999999"));
            new Thread(() =>
            {
                IPEndPoint ipe = new IPEndPoint(Runtime.ip, msgInPort);
                Socket sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    sSocket.Connect(ipe);
                    Console.WriteLine("连接本地服务成功！");
                    sSocket.Send(bytes);
                    byte[] back = new byte[socketLenght];
                    string bac = null;
                    while (bac == null)
                    {
                        sSocket.Receive(back);
                        bac = Encoding.UTF8.GetString(back);
                        new SCLanHandle(sSocket, back);
                    }
                }
                catch
                {
                    Console.WriteLine("连接本地服务失败！");
                }
                finally
                {
                    if (sSocket.Connected)
                    {
                        sSocket.Shutdown(SocketShutdown.Both);
                        sSocket.Close();
                        sSocket.Dispose();
                    }
                }
            }).Start();
        }

        public static void SendMsgNoWait(byte[] bytes)
        {
            IPEndPoint ipe = new IPEndPoint(Runtime.ip, msgInPort);
            Socket sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                sSocket.Connect(ipe);
                Console.WriteLine("连接本地服务成功！");
                try
                {
                    sSocket.Send(bytes);
                    sSocket.Close();
                }
                catch (Exception ex)
                {
                    Console.Out.WriteLine(ex.ToString());
                    sSocket.Shutdown(SocketShutdown.Both);
                    sSocket.Close();
                    sSocket.Dispose();
                }
            }
            catch
            {
                Console.WriteLine("连接本地服务失败！");
                return;
            }
        }
    }
}
